package demo.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import demo.bo.BrandCreateBo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import demo.entity.BrandEntity;
import demo.service.BrandService;
import demo.utils.CommonResult;
import demo.utils.PageUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;


/**
 * 
 *
 * @author may
 * @email 
 * @date 2023-05-09 16:06:07
 */
@RestController
@RequestMapping("demo/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @GetMapping("/list")
    //@RequiresPermissions("ecbe:brand:list")
    public CommonResult list(@RequestParam(value="brandName",required = false) String brand_name,
                             @RequestParam(value="status",required = false) Integer status,
                             @RequestParam(value="page",defaultValue = "1") Integer page,
                             @RequestParam(value="size",defaultValue = "10") Integer size){
        Map<String, Object> params = new HashMap<>(20);
        if(StringUtils.isNotBlank(brand_name)){
            params.put("brandName",brand_name);
        }else{
            params.put("brandName",null);
        }
        if(status != null){
            params.put("status",status);
        }else{
            params.put("status",null);
        }

        params.put("page",page);
        params.put("limit",size);

        PageUtils data = brandService.queryPage(params);

        return CommonResult.success(data);
    }


    /**
     * 保存
     */
    @PostMapping("/create")
    //@RequiresPermissions("ecbe:brand:save")
    public CommonResult save(@RequestBody BrandCreateBo brand, HttpServletRequest request){

        if("".equals(brand.getBrand_name()) || StringUtils.isBlank(brand.getBrand_name())){
            return CommonResult.failed("品牌名称不能为空");
        }
        if("".equals(brand.getImg_url()) || StringUtils.isBlank(brand.getImg_url())){
            return CommonResult.failed("品牌图片不能为空");
        }
        if("".equals(brand.getIcon_url()) || StringUtils.isBlank(brand.getIcon_url())){
            return CommonResult.failed("品牌icon不能为空");
        }

		BrandEntity brandEntity = new BrandEntity();
        BeanUtils.copyProperties(brand,brandEntity);

        //获取当前登录用户的信息
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request);
        Long userId = Long.valueOf(requestWrapper.getHeader("userId"));
        brandEntity.setCreator_id(userId);

        brandEntity.setCreated_at(new Date());
        //状态默认设置为0 未使用
        brandEntity.setStatus(0);

        boolean createResult = brandService.save(brandEntity);

        return CommonResult.success(createResult);
    }


}
